package com.alliance.shuwei.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alliance.shuwei.entity.Role;
import com.alliance.shuwei.repository.RoleDao;

@Controller
@RequestMapping("/admin/roles")
public class RoleController {
	private final RoleDao roleDao;

	@Autowired
	public RoleController(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public Role addRole(@Valid Role role) {
		return roleDao.save(role);
	}

	@RequestMapping(value = "{id}", params = "isActive", method = RequestMethod.POST)
	public void updateRoleStatus(@PathVariable("id") Integer id, @RequestParam String active) {
		Role role = roleDao.findOne(id);
		if ("Active".equalsIgnoreCase(active)) {
			role.setActive(true);
		} else {
			role.setActive(false);
		}
		roleDao.save(role);
	}

	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<Role> getAllRoles() {
		List<Role> roles = new ArrayList<Role>();
		Iterator<Role> iterator = roleDao.findAll().iterator();
		while (iterator.hasNext()) {
			roles.add(iterator.next());
		}
		return roles;
	}
}
